package com.zlt.bkparking.controller.salesman;

import com.zlt.bkparking.dto.AdvertisementDTO;
import com.zlt.bkparking.service.AdvertisementService;
import com.zlt.bkparking.utils.StringUtil;
import com.zlt.bkparking.vo.AdvertisementVO;
import com.zlt.bkparking.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("advertisement")
public class AdvertisementController {

    @Autowired
    private AdvertisementService advertisementService;

    /**
     * 上传广告文件
     * @return
     */
    @PostMapping("uploadAdvertisement")
    public Result uploadAdvertisement(@RequestParam("file") MultipartFile file){
        String path = getClass().getClassLoader().getResource("static/files").getPath();
        File f = new File(path);
        if (!f.exists()){
            f.mkdirs();
        }
        String originalFilename = file.getOriginalFilename();
        String fileName = StringUtil.uuid() + originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileUrl = "http://localhost/files/" + fileName;
        try {
            file.transferTo(new File(path,fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.ok("上传广告成功",fileUrl);
    }

    /**
     * 查询广告列表
     * @return
     */
    @GetMapping
    public Result showAdvertisementList() {
        List<AdvertisementVO> advertisementVOList = advertisementService.showAdvertisementList();
        return Result.ok("查询广告列表成功", advertisementVOList);
    }

    /**
     * 添加广告
     * @return
     */
    @PostMapping
    public Result addAdvertisement(AdvertisementDTO advertisementDTO) {
        boolean success = advertisementService.addAdvertisement(advertisementDTO);
        return success ? Result.ok("添加广告成功") : Result.error("添加广告失败");
    }

    /**
     * 下架广告
     * @param adId
     * @return
     */
    @GetMapping("undercarriageAdvertisement")
    public Result undercarriageAdvertisement(String adId) {
        boolean success = advertisementService.undercarriageAdvertisement(Long.parseLong(adId));
        return success ? Result.ok("下架广告成功") : Result.error("下架广告失败");
    }
}
